<template>
  <div>
    <a-breadcrumb style="margin-bottom: 10px">
      <a-breadcrumb-item>
        <icon-menu-unfold />
      </a-breadcrumb-item>
      <a-breadcrumb-item>运维管理</a-breadcrumb-item>
      <a-breadcrumb-item>维保记录</a-breadcrumb-item>
    </a-breadcrumb>
    <a-card>
      <!-- 查询条件 start -->
      <a-row>
        <a-col :flex="1" style="margin-top: 4px">
          <a-form :model="searchModel" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }" label-align="left" auto-label-width>
            <a-row :gutter="8">
              <a-col :span="6">
                <a-form-item label="维保时间">
                  <a-range-picker v-model="searchModel.time" />
                </a-form-item>
              </a-col>
              <a-divider style="height: 40px; margin-bottom: 12px" direction="vertical" />
              <a-col :span="6">
                <a-form-item hide-label>
                  <a-button type="primary" @click="search">
                    <template #icon>
                      <icon-search />
                    </template>
                    {{ '查询' }}
                  </a-button>
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </a-col>
      </a-row>
      <!-- 查询条件 end -->
      <!-- 分割线 -->
      <a-divider style="margin-top: 0" />
      <!-- 操作按钮 start -->
      <a-row style="margin-bottom: 16px">
        <a-col :span="12">
          <a-space>
            <a-button type="primary" @click="handleAdd">
              <template #icon>
                <icon-plus />
              </template>
              {{ '新建维保' }}
            </a-button>
          </a-space>
        </a-col>
      </a-row>
      <!-- 操作按钮 end -->
      <!-- 表格内容 start -->
      <a-table row-key="id" ref="tableRef" :loading="loading" :bordered="{ wrapper: true, cell: true }" :columns="columns" :data="renderData" @page-change="onPageChange" :pagination="pagination" @page-size-change="onPageSizeChange">
        <!-- 设备 -->
        <template #deviceIdFor="{ record }">
          {{ record.deviceIdFor.map((item: any) => item.name).join(',') }}
        </template>
        <template #operate="{ record }">
          <a-button size="small" type="text" status="success" @click="handleUpdate(record.id)">
            {{ '编辑' }}
          </a-button>
          <a-button size="small" type="text" status="danger" @click="handleDelete(record)">
            {{ '删除' }}
          </a-button>
          <a-button size="small" type="text" status="success" @click="handleDetail(record.id)">
            {{ '详情' }}
          </a-button>
        </template>
      </a-table>
      <!-- 添加/编辑维保 -->
      <a-drawer :width="700" :esc-to-close="false" :ok-loading="formDrawer.loading" :visible="formDrawer.visible" @cancel="handleFormCancel" @ok="handleSubmitForm" :mask-closable="false">
        <template #title>
          {{ formDrawer.formModel.id ? '编辑' : '新建维保' }}
        </template>
        <a-spin :loading="formDrawer.loading" style="width: 100%; height: auto">
          <a-form ref="formRef" auto-label-width :model="formDrawer.formModel" label-align="right" v-model:rules="formDrawer.rules">
            <!-- 维保名称 -->
            <a-form-item field="maintainTitle" label="维保名称">
              <a-input v-model="formDrawer.formModel.maintainTitle" placeholder="请输入维保名称" />
            </a-form-item>
            <!-- 站点名称 -->
            <a-form-item field="stationName" label="站点名称">
              <a-input v-model="formDrawer.formModel.stationName" placeholder="请输入站点名称" />
            </a-form-item>
            <!-- 关联设备 -->
            <a-form-item field="deviceIdFor" label="关联设备">
              <a-space direction="vertical" fill :size="16">
                <!-- 添加按钮 -->
                <a-button type="primary" @click="handleDeviceAdd">
                  <template #icon>
                    <icon-plus />
                  </template>
                  {{ '添加设备' }}
                </a-button>
                <a-table row-key="value" :bordered="{ wrapper: true, cell: true }" :pagination="false" :data="formDrawer.formModel.deviceIdFor" :columns="deviceColumns" v-bind:hide-expand-button-on-empty="true">
                  <template #operate="{ rowIndex }">
                    <a-button size="small" type="primary" status="danger" @click="handleDeviceDel(rowIndex)">
                      {{ '移除' }}
                    </a-button>
                  </template>
                </a-table>
              </a-space>
            </a-form-item>
            <!-- 维保人员 -->
            <a-form-item field="userNameFor" label="维保人员">
              <a-input v-model="formDrawer.formModel.userNameFor" placeholder="请输入维保人员" />
            </a-form-item>
            <!-- 维保时间 -->
            <a-form-item field="maintainTime" label="维保时间">
              <a-date-picker show-time v-model="formDrawer.formModel.maintainTime" format="YYYY-MM-DD HH:mm:ss" />
            </a-form-item>
          </a-form>
        </a-spin>
      </a-drawer>
      <!-- 维保详情 start -->
      <a-drawer :width="700" :esc-to-close="false" :visible="formDrawer.detailVisible" @ok="handleFormCancel" @cancel="handleFormCancel" :mask-closable="false">
        <template #title>
          {{ '维保详情' }}
        </template>
        <a-spin :loading="formDrawer.loading" style="width: 100%; height: auto">
          <a-row>
            <a-col style="height: 100vh">
              <a-descriptions :align="{ label: 'right' }" :label-style="{ color: 'rgb(var(--color-neutral-10))' }" :column="1" size="large">
                <!-- 维保名称 -->
                <a-descriptions-item label="维保名称：">
                  <span>{{ formDrawer.formModel.maintainTitle }}</span>
                </a-descriptions-item>
                <!-- 站点名称 -->
                <a-descriptions-item label="站点名称：">
                  <span>{{ formDrawer.formModel.stationName }}</span>
                </a-descriptions-item>
                <!-- 维保设备 -->
                <a-descriptions-item label="维保设备：">
                  <a-skeleton v-if="formDrawer.loading" :animation="true">
                    <a-skeleton-line :rows="1" />
                  </a-skeleton>
                  <span v-else>
                    <a-table :bordered="{ wrapper: true, cell: true }" :data="formDrawer.formModel.deviceIdFor" :pagination="false">
                      <template #columns>
                        <a-table-column title="设备名称" data-index="name" />
                        <a-table-column title="设备编码" data-index="value" />
                      </template>
                    </a-table>
                  </span>
                </a-descriptions-item>
                <!-- 维保人员 -->
                <a-descriptions-item label="维保人：">
                  <span>{{ formDrawer.formModel.userNameFor }}</span>
                </a-descriptions-item>
                <!-- 维保时间 -->
                <a-descriptions-item label="维保时间：">
                  <span>{{ formDrawer.formModel.maintainTime }}</span>
                </a-descriptions-item>
              </a-descriptions>
            </a-col>
          </a-row>
        </a-spin>
      </a-drawer>
      <!-- 选择设备 start -->
      <a-modal width="600px" :visible="modalModel.visible" :footer="false" title-align="start" title="某光伏发电站" @cancel="handleModalClose">
        <a-row style="margin-bottom: 16px">
          <a-col style="text-align: center">
            <a-tabs v-model:active-key="tabsActiveKey" @change="handleTabsChange">
              <a-tab-pane v-for="(item, index) in tabsList" :key="item.value" :title="item.key" />
            </a-tabs>
            <a-table ref="tableDeviceRef" :bordered="{ wrapper: true, cell: true }" :scroll="{ y: 500 }" :pagination="false" :data="modalModel.renderData" :columns="deviceModalColumns" v-bind:hide-expand-button-on-empty="true" :default-expand-all-rows="true">
              <template #operate="{ record }">
                <a-button v-if="record.isGroup == 0" size="small" type="primary" @click="handleDeviceSelect(record)">选择</a-button>
              </template>
            </a-table>
          </a-col>
        </a-row>
      </a-modal>
      <!-- 选择设备 end -->
      <!-- 操作弹框 start -->
      <a-modal width="450px" v-model:visible="operateModalModel.visible" class="modal-box">
        <template #title>
          <icon-close-circle v-if="operateModalModel.type == 1" size="18" style="color: rgb(var(--red-6)); margin-right: 5px" />
          <icon-exclamation-circle v-else size="18" style="color: rgb(var(--orange-6)); margin-right: 5px" />
          确认提示
        </template>
        <div style="text-align: center">是否确认{{ operateModalModel.title }}名称为【{{ operateModalModel.name }}】的数据项？</div>
        <template #footer>
          <div style="text-align: center">
            <a-space>
              <a-button type="primary" status="danger" @click="handleOperateModelCancle">取消</a-button>
              <a-button type="primary" @click="handleOperateModelOk">确认</a-button>
            </a-space>
          </div>
        </template>
      </a-modal>
      <!-- 操作弹框 end -->
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import dayjs from 'dayjs'
import useLoading from '../../utils/loading'
import { BasePagination } from '../../apis/common'
import { listMaintenance, addMaintenance, updateMaintenance, deleteMaintenance } from '../../apis/Operationmanage'
import { FormInstance, TableInstance, Message } from '@arco-design/web-vue'
import { listDevice, listFusionGroup } from '../../apis/device'

const { loading, setLoading } = useLoading(true)

// 获取当前时间
const dateNow = dayjs().format('YYYY-MM-DD')
const dateBefore = dayjs().subtract(1, 'month').format('YYYY-MM-DD')

// 生成查询条件对象
const generateSearchModel = () => {
  return {
    time: [dateBefore, dateNow]
  }
}

// 查询表单对象
const searchModel = ref(generateSearchModel())

// 设置表格列
const columns = computed<any[]>(() => [
  {
    title: '维保名称',
    dataIndex: 'maintainTitle',
    align: 'center',
    fixed: 'left',
    width: 200
  },
  {
    title: '站点',
    dataIndex: 'stationName',
    width: 150,
    align: 'center'
  },
  {
    title: '设备',
    dataIndex: 'deviceIdFor',
    slotName: 'deviceIdFor',
    width: 200,
    align: 'center'
  },
  {
    title: '维保人',
    dataIndex: 'userNameFor',
    slotName: 'userNameFor',
    align: 'center',
    width: 200
  },
  {
    title: '维保时间',
    dataIndex: 'maintainTime',
    slotName: 'maintainTime',
    width: 180,
    align: 'center'
  },
  {
    title: '操作',
    dataIndex: 'operations',
    width: 180,
    slotName: 'operate',
    align: 'center'
  }
])

// 表格数据
const renderData = ref<any[]>([])

// 表格分页参数
const pagination: any = reactive({ ...BasePagination() })

// 表格页码发生变化
const onPageChange = async (val: number) => {
  pagination.current = val
  await fetchData()
}

// 表格每页数量发生变化
const onPageSizeChange = async (val: number) => {
  pagination.pageSize = val
  await fetchData()
}

/**
 * 获取表格数据
 */
const fetchData = async () => {
  setLoading(true)
  try {
    const params = {
      beginTime: dayjs(searchModel.value.time[0]).format('YYYY-MM-DD 00:00:00'),
      endTime: dayjs(searchModel.value.time[1]).format('YYYY-MM-DD 23:59:59'),
      pageNum: pagination.current,
      pageSize: pagination.pageSize
    }
    const res: any = await listMaintenance(params)
    if (res.data.code === 200) {
      renderData.value = res.data.rows
      pagination.total = res.data.total
    }
  } catch (err) {
    console.error('维保记录列表-错误', err)
    Message.error('获取维保记录列表失败')
  } finally {
    setLoading(false)
  }
}

onMounted(async () => {
  await fetchData()
})

// 查询
const search = async () => {
  pagination.current = 1
  await fetchData()
}

// 生成表单模型
const generateFormDrawerModel = () => {
  return {
    visible: false,
    detailVisible: false,
    loading: false,
    rules: {
      maintainTitle: [{ required: true, message: '请输入维保名称' }],
      stationName: [{ required: true, message: '请输入站点名称' }],
      deviceIdFor: [{ required: true, message: '请选择设备' }],
      userNameFor: [{ required: true, message: '请输入维保人员' }],
      maintainTime: [{ required: true, message: '请选择维保时间' }]
    },
    formModel: {
      id: 0,
      stationType: 2,
      /** 维保名称 */
      maintainTitle: undefined,
      /**站点 */
      stationId: undefined,
      stationName: '',
      /** 维保人员 */
      userIds: '',
      userNameFor: '',
      /**维保时间 */
      maintainTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      /**设备列表 */
      deviceIdFor: []
    }
  }
}

// 表单模型
const formDrawer = ref(generateFormDrawerModel())

// 设备列表-列
const deviceColumns = computed<any[]>(() => [
  {
    title: '设备名称',
    dataIndex: 'name',
    align: 'left',
    fixed: 'left',
    width: 250
  },
  {
    title: '设备编码',
    dataIndex: 'value',
    align: 'left',
    fixed: 'left',
    width: 250
  },
  {
    title: '操作',
    dataIndex: 'operate',
    width: 80,
    slotName: 'operate',
    align: 'center',
    fixed: 'right'
  }
])

/**
 * 添加维保记录
 */
const handleAdd = async () => {
  formDrawer.value = generateFormDrawerModel()
  formDrawer.value.visible = true
}

/**
 * 表单取消
 */
const handleFormCancel = () => {
  formDrawer.value = generateFormDrawerModel()
}

const formRef = ref<FormInstance>()

/**
 * 表单提交
 */
const handleSubmitForm = async () => {
  // 校验表单
  const validate = await formRef.value?.validate()
  if (!validate) return

  setLoading(true)
  try {
    // 修正：合并重复的formData定义
    const formData = {
      ...formDrawer.value.formModel,
      maintainTime: dayjs(formDrawer.value.formModel.maintainTime).format('YYYY-MM-DD HH:mm:ss'),
      deviceIds: formDrawer.value.formModel.deviceIdFor.map(item => item.value).join(','),
      userIds: formDrawer.value.formModel.userIds
    }

    let res: any
    if (formDrawer.value.formModel.id === 0) {
      // 新建维保记录
      res = await addMaintenance(formData)
      if (res.data.code === 200) {
        Message.success('新建维保记录成功')
        formDrawer.value.visible = false
        await fetchData()
      }
    } else {
      // 编辑维保记录
      res = await updateMaintenance(formData)
      if (res.data.code === 200) {
        Message.success('编辑维保记录成功')
        formDrawer.value.visible = false
        await fetchData()
      }
    }
  } catch (err) {
    console.error('维保记录操作-错误', err)
    Message.error('操作失败')
  } finally {
    setLoading(false)
  }
}

// 选择设备模型
const generateModalModel = () => {
  return {
    visible: false,
    pvGroupName: '',
    // 表格数据
    renderData: []
  }
}

// 设备弹框模型
const modalModel = ref(generateModalModel())

// 表格实例
const tableDeviceRef = ref<TableInstance>()

// tab集合
const tabsList = ref<any>([])

const deviceModalColumns = computed<any[]>(() => [
  {
    title: '设备名称',
    dataIndex: 'deviceName',
    slotName: 'deviceName',
    align: 'left',
    width: 200
  },
  {
    title: '设备编码',
    dataIndex: 'deviceSn',
    slotName: 'deviceSn',
    align: 'center',
    width: 200
  },
  {
    title: '操作',
    dataIndex: 'operate',
    slotName: 'operate',
    width: 120,
    align: 'center',
    fixed: 'right'
  }
])

/**
 * 选择设备关闭
 */
const handleModalClose = () => {
  modalModel.value = generateModalModel()
}

/**
 * 选择设备
 */
const handleDeviceAdd = async () => {
  modalModel.value.visible = true
  // 获取tabList
  await fetchTabData()
  // 获取设备列表
  await fetchDeviceData()
}

// 选中的tab
const tabsActiveKey = ref<any>(0)

/**
 * table切换
 */
const handleTabsChange = async () => {
  modalModel.value.pvGroupName = tabsList.value.find((item: any) => item.value === tabsActiveKey.value).key
  await fetchDeviceData()
  tableDeviceRef.value?.expandAll(true)
}

/**
 * 获取tab
 */
const fetchTabData = async () => {
  try {
    const res = await listDevice()
    if (res.data.code === 200) {
      tabsList.value = res.data.data
      tabsActiveKey.value = res.data.data[0].value
      await handleTabsChange()
    }
  } catch (error) {
    console.error('获取设备tab失败', error)
  }
}

/**
 * 获取设备列表
 */
const fetchDeviceData = async () => {
  try {
    const res = await listFusionGroup({
      groupName: modalModel.value.pvGroupName
    })
    modalModel.value.renderData = res.data.data
    tableDeviceRef.value?.expandAll(true)
  } catch (err) {
    console.log('维保管理-设备列表-错误', err)
  }
}

/**
 * 设备选中
 * @param record
 */
const handleDeviceSelect = (record: any) => {
  let info: any = formDrawer.value.formModel.deviceIdFor.find((item) => item.value === record.deviceSn)
  if (!info) {
    formDrawer.value.formModel.deviceIdFor.push({
      name: record.deviceName,
      value: record.deviceSn
    })
  }
  // 关闭弹框
  modalModel.value.visible = false
}

/**
 * 移除设备
 * @param val
 */
const handleDeviceDel = (val: number) => {
  formDrawer.value.formModel.deviceIdFor.splice(val, 1)
}

// 操作弹框
const generateOperateModalModel = () => {
  return {
    type: 0,
    visible: false,
    title: '',
    id: 0,
    value: 0,
    name: ''
  }
}

// 操作弹框模型
const operateModalModel = ref(generateOperateModalModel())

/**
 * 删除数据
 * @param record 数据行
 */
const handleDelete = (record: any) => {
  operateModalModel.value.visible = true
  operateModalModel.value.id = record.id
  operateModalModel.value.title = '删除'
  operateModalModel.value.name = record.maintainTitle
}

/**
 * 删除提示弹框取消
 */
const handleOperateModelCancle = () => {
  operateModalModel.value = generateOperateModalModel()
}

/**
 * 删除提示弹框确认
 */
const handleOperateModelOk = async () => {
  operateModalModel.value.visible = false
  setLoading(true)
  try {
    const res: any = await deleteMaintenance({ id: operateModalModel.value.id })
    if (res.data.code === 200) {
      Message.success('删除成功')
      await fetchData()
    }
  } catch (err) {
    console.error('删除维保记录-错误', err)
    Message.error('删除失败')
  } finally {
    setLoading(false)
  }
}

/**
 * 编辑维保记录
 */
const handleUpdate = (id: number) => {
  formDrawer.value.visible = true
  const record = renderData.value.find((item) => item.id === id)
  if (record) {
    formDrawer.value.formModel = {
      ...record,
      maintainTime: dayjs(record.maintainTime).toDate()
    }
  }
}

/**
 * 查看详情
 */
const handleDetail = (id: number) => {
  formDrawer.value.detailVisible = true
  const record = renderData.value.find((item) => item.id === id)
  if (record) {
    formDrawer.value.formModel = {
      ...record,
      maintainTime: dayjs(record.maintainTime).toDate()
    }
  }
}
</script>